<template>
  <el-dialog
    v-el-drag-dialog
    :title="title+'报价'"
    :visible.sync="visible"
    width="1200px"
    @closed="reset"
  >
    <el-descriptions title="司机信息" size="medium" :column="3" :label-style="labelStyle" :content-style="contentStyle">
      <el-descriptions-item label="绑定司机编号">{{ dataForm.driverCode }}</el-descriptions-item>
      <el-descriptions-item label="绑定司机">{{ dataForm.driverName }}</el-descriptions-item>
      <el-descriptions-item label="司机所属机构">{{ dataForm.orgName }}</el-descriptions-item>
    </el-descriptions>
    <div>
      <div>历史报价信息:
        <el-radio-group v-model="query.expired" style="margin: 0 0 10px 10px;" @change="fetchData({ currentPage: 1, pageSize: 20 })">
          <el-radio :label="2">未过期</el-radio>
          <el-radio :label="1">过期</el-radio>
        </el-radio-group>
      </div>
      <lb-table
        ref="lbTable"
        v-loading="$loadingPlugin.fetchData"
        class="table-list"
        border
        element-loading-text="加载中"
        :column="column"
        :data="tableData.data"
        :total="tableData.total"
        custom-column
        :immediate-fetch="false"
        pagination
        :span-method="objectSpanMethod"
        @expand-change="expandChange"
        @select="handleSelectionChange"
        @fetch="fetchData"
      />
    </div>
    <el-form ref="dataForm" inline class="form" style="margin-top: 20px;" :model="dataForm" :rules="rules" label-position="left">
      <el-form-item label="商品分类：" prop="gTypeId" style="width: 300px;">
        <el-select
          v-model="dataForm.gtId"
          placeholder="请选择商品分类"
          :disabled="goodsDisabled"
          @change="goodsTypeChange"
        >
          <el-option
            v-for="item in goodTypeList"
            :key="item.value"
            :label="item.gtName"
            :value="item.gtId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="商品选择：" prop="goods" style="width: 300px;">
        <el-select
          v-model="dataForm.goodsId"
          placeholder="请选择商品选择"
          :multiple="multiple"
          :disabled="goodsDisabled"
          clearable
          @change="goodsChange"
        >
          <el-option
            v-for="(item, index) in goodsList"
            :key="index"
            :value="item.goodsId"
            :label="item.goodsName"
          />
        </el-select>
      </el-form-item>
      <!-- 上楼费 -->
      <div>
        <div class="title">上楼费:</div>
        <el-form-item label="居民用户:" prop="" style="width: 100%;">
          <el-radio-group v-model="resident.floorType" @change="changeResidentFloor">
            <el-radio v-model="resident.floorType" :disabled="formDisabled" :label="1">市场价</el-radio>
            <el-radio v-model="resident.floorType" :disabled="formDisabled" :label="2">市场价打折</el-radio>
            <el-select v-show="resident.floorType===2" v-model="resident.floorDisCount" :disabled="formDisabled" style="width: 120px; margin-right: 20px;" placeholder="请选择" @change="$forceUpdate()">
              <el-option
                v-for="item in discountList"
                :key="item.value"
                :label="item.desc"
                :value="item.value"
              />
            </el-select>
            <el-radio v-model="resident.floorType" :disabled="formDisabled" :label="3">固定价格（元）</el-radio>
            <el-input-number v-if="resident.floorType===3" v-model="resident.floorFee" :disabled="formDisabled" :controls="false" :min="0" :max="10000" :precision="2" size="mini" placeholder="请输入" />
          </el-radio-group>
        </el-form-item>
        <el-form-item label="非居民用户:" prop="" style="width: 100%;">
          <el-radio-group v-model="business.floorType" @change="changeBusinessFloor">
            <el-radio v-model="business.floorType" :disabled="formDisabled" :label="1">市场价</el-radio>
            <el-radio v-model="business.floorType" :disabled="formDisabled" :label="2">市场价打折</el-radio>
            <el-select v-if="business.floorType===2" v-model="business.floorDisCount" :disabled="formDisabled" style="width: 120px; margin-right: 20px;" placeholder="请选择" @change="$forceUpdate()">
              <el-option
                v-for="item in discountList"
                :key="item.value"
                :label="item.desc"
                :value="item.value"
              />
            </el-select>
            <el-radio v-model="business.floorType" :disabled="formDisabled" :label="3">固定价格（元）</el-radio>
            <el-input-number v-if="business.floorType===3" v-model="business.floorFee" :disabled="formDisabled" :controls="false" :min="0" :max="10000" :precision="2" size="mini" placeholder="请输入" />
          </el-radio-group>
        </el-form-item>
      </div>
      <!-- 配送费 -->
      <div>
        <div class="title">配送费:</div>
        <el-form-item label="居民用户:" prop="">
          <el-radio-group v-model="resident.feeType" style="margin-bottom: 10px;" @change="changeResidentFee">
            <el-radio :label="1" :disabled="formDisabled">市场价</el-radio>
            <el-radio :label="2" :disabled="formDisabled">市场价打折</el-radio>
            <el-select v-show="resident.feeType===2" v-model="resident.disCount" style="width: 120px; margin-right: 20px;" placeholder="请选择" :disabled="formDisabled" @change="$forceUpdate()">
              <el-option
                v-for="item in discountList"
                :key="item.value"
                :label="item.desc"
                :value="item.value"
              />
            </el-select>
            <el-radio :label="3" :disabled="formDisabled">固定价格（元）</el-radio>
            <el-input-number v-show="resident.feeType===3" v-model="resident.fee" style="margin-right: 20px;" :controls="false" :min="0" :max="10000" :precision="2" size="mini" placeholder="请输入" :disabled="formDisabled" />
            <el-radio :label="4" :disabled="formDisabled">按距离设置配送费用</el-radio>
            <span v-show="resident.feeType===4" style="font-size: 14px;">选择距离阶梯档次: </span>
            <el-select v-show="resident.feeType===4" v-model="resident.disCount1" style="width: 120px;" placeholder="请选择" :disabled="formDisabled" @change="changeResidentDistanceJson">
              <el-option
                v-for="item in [{desc:'二档', value:1},{desc:'三档', value:2},{desc:'四档', value:3},{desc:'五档', value:4},{desc:'六档', value:5}]"
                :key="item.value"
                :label="item.desc"
                :value="item.value"
              />
            </el-select>
          </el-radio-group>
          <div v-show="resident.feeType===4" style="width: 100%; padding-left: 30px;">
            <p v-for="(item,index) in resident.deliverList" :key="index" style="margin-bottom: 10px;">配送距离在
              <el-input-number v-model="item.startDistance" :disabled="!index || formDisabled" :controls="false" :min="0" :max="10000" :precision="2" @blur="feeChange(resident.deliverList,index)" />公里至
              <el-input-number v-model="item.endDistance" :disabled="formDisabled" :controls="false" :min="0" :max="10000" :precision="2" @blur="feeEndChange(resident.deliverList,index,resident)" />公里（包含）至收取配送费
              <el-input-number v-model="item.fee" :disabled="formDisabled" :controls="false" :min="0" :max="10000" :precision="2" />元</p>
            <p>配送距离超过<el-input-number v-model="resident.exceedDistance" :controls="false" :min="0" :max="10000" :precision="2" disabled />公里收取配送费<el-input-number v-model="resident.fixedFee" :disabled="formDisabled" :controls="false" :min="0" :max="10000" :precision="2" />元</p>
          </div>
        </el-form-item>
        <el-form-item label="非居民用户:" prop="">
          <el-radio-group v-model="business.feeType" style="margin-bottom: 10px;" @change="changeBusinessFee">
            <el-radio :label="1" :disabled="formDisabled">市场价</el-radio>
            <el-radio :label="2" :disabled="formDisabled">市场价打折</el-radio>
            <el-select v-show="business.feeType===2" v-model="business.disCount" :disabled="formDisabled" style="width: 120px; margin-right: 20px;" placeholder="请选择" @change="$forceUpdate()">
              <el-option
                v-for="item in discountList"
                :key="item.value"
                :label="item.desc"
                :value="item.value"
              />
            </el-select>
            <el-radio :disabled="formDisabled" :label="3">固定价格（元）</el-radio>
            <el-input-number v-show="business.feeType===3" v-model="business.fee" :disabled="formDisabled" style="margin-right: 20px;" :controls="false" :min="0" :max="10000" :precision="2" size="mini" placeholder="请输入" />
            <el-radio :disabled="formDisabled" :label="4">按距离设置配送费用</el-radio>
            <span v-show="business.feeType===4" style="font-size: 14px;">选择距离阶梯档次: </span>
            <el-select v-show="business.feeType===4" v-model="business.disCount1" style="width: 120px;" placeholder="请选择" :disabled="formDisabled" @change="changeBusinessDistanceJson">
              <el-option
                v-for="item in [{desc:'二档', value:1},{desc:'三档', value:2},{desc:'四档', value:3},{desc:'五档', value:4},{desc:'六档', value:5}]"
                :key="item.value"
                :label="item.desc"
                :value="item.value"
              />
            </el-select>
          </el-radio-group>
          <div v-show="business.feeType===4" style="width: 100%; padding-left: 30px;">
            <p v-for="(item,index) in business.deliverList" :key="index" style="margin-bottom: 10px;">配送距离在
              <el-input-number v-model="item.startDistance" :disabled="!index || formDisabled" :controls="false" :min="0" :max="10000" :precision="2" @blur="feeChange(business.deliverList,index)" />公里至
              <el-input-number v-model="item.endDistance" :disabled="formDisabled" :controls="false" :min="0" :max="10000" :precision="2" @blur="feeEndChange(business.deliverList,index,business)" />公里（包含）至收取配送费
              <el-input-number v-model="item.fee" :disabled="formDisabled" :controls="false" :min="0" :max="10000" :precision="2" />元</p>
            <p>配送距离超过<el-input-number v-model="business.exceedDistance" :controls="false" :min="0" :max="10000" :precision="2" disabled />公里收取配送费<el-input-number v-model="business.fixedFee" :disabled="formDisabled" :controls="false" :min="0" :max="10000" :precision="2" />元</p>
          </div>
        </el-form-item>
      </div>

      <el-form-item label="" prop="timeType" style="width: 58%;">
        <div class="title">生效时间:</div>
        <el-radio-group v-model="dataForm.timeType" @change="changeTimeType">
          <el-radio :disabled="formDisabled" :label="1">有效期</el-radio>
          <el-date-picker
            v-if="dataForm.timeType===1"
            v-model="date"
            :disabled="formDisabled"
            style="width: 63%; margin-right: 20px;"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd HH:mm:ss"
            :default-time="['00:00:00', '23:59:59']"
            :clearable="false"
          />
          <el-radio :disabled="formDisabled" :label="2">长期</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="" prop="containType" style="width: 38%;">
        <div class="title">涉及的该大车用户:</div>
        <el-radio-group v-model="dataForm.containType">
          <el-radio :disabled="formDisabled" :label="1">所有用户</el-radio>
          <el-radio :disabled="formDisabled" :label="2">该大车司机的用户单独设置过价格的不涉及</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <div v-show="title!=='查看'" slot="footer" class="dialog-footer">
      <el-button :loading="$loadingPlugin.del" @click="cancel('dataForm')">
        取消
      </el-button>
      <el-button :loading="$loadingPlugin.success" :type="title==='删除'? 'danger': 'primary'" @click="sumbit('dataForm',title)">
        保存
      </el-button>
    </div>
  </el-dialog>
</template>
<script>
  import { queryDriverPriceInfo, queryDriverPriceInfoList, saveDriverPrice, deleteDriverPrice, goodsTypeQueryAllList, goodsTypeDetail } from '@/api'
  import { parseTime, formatColumnMap } from '@/utils'
  export default {
    components: {

    },
    props: {
      parentFetchData: {
        type: Function
      }
    },
    data() {
      return {
        title: '设置',
        visible: false,
        formDisabled: false,
        multiple: true,
        goodsDisabled: false,
        goodTypeList: [],
        goodsList: [],
        discountList: [
          { desc: '1折', value: 0.1 },
          { desc: '2折', value: 0.2 },
          { desc: '3折', value: 0.3 },
          { desc: '4折', value: 0.4 },
          { desc: '5折', value: 0.5 },
          { desc: '6折', value: 0.6 },
          { desc: '7折', value: 0.7 },
          { desc: '8折', value: 0.8 },
          { desc: '9折', value: 0.9 }
        ],
        feeTypeMap: [{ desc: '市场价', value: 1 }, { desc: '市场价打折', value: 2 }, { desc: '固定价格（元）', value: 3 }, { desc: '按距离设置配送费用', value: 4 }],
        floorTypeMap: [{ desc: '市场价', value: 1 }, { desc: '市场价打折', value: 2 }, { desc: '固定价格（元）', value: 3 }],
        temp: {},
        query: {
          expired: 2
        },
        tableData: {
          total: 0,
          data: []
        },
        dataForm: {
          driverCode: '',
          driverName: '',
          orgName: '',
          timeType: null,
          goodsId: [],
          gtId: null,
          containType: null
        },
        rules: {
          residentFeeType: [{ required: true, message: '请选择居民配送费优惠方案', trigger: 'change' }],
          businessFeeType: [{ required: true, message: '请选择商业配送费优惠方案', trigger: 'change' }]
        },
        date: '',
        resident: {
          disCount: null,
          fee: 0.00,
          exceedDistance: 0.00,
          fixedFee: 0.00,
          floorDisCount: null,
          floorFee: 0.00,
          disCount1: 2,
          feeType: 1,
          floorType: 1,
          deliverList: []
        },
        business: {
          disCount: null,
          fee: 0.00,
          exceedDistance: 0.00,
          fixedFee: 0.00,
          floorDisCount: null,
          floorFee: 0.00,
          disCount1: 2,
          feeType: 1,
          floorType: 1,
          deliverList: []
        },
        labelStyle: { 'white-space': 'nowrap' },
        contentStyle: { 'word-break': 'break-all' }
      }
    },
    computed: {
      column: function() {
        return [
          // {
          //   type: 'expand',
          //   render: (h, { row, $index, column }) => {
          //     return (
          //       <div>
          //        {this.detailList[row.categoryDetailId] && this.detailList[row.categoryDetailId].map(item => {
          //          return <div class='detail-marge'>
          //           <span>【{ item.createTime && this.formatDate(item.createTime) }】</span>
          //           <span>操作员【{ item.createUser}】</span>
          //           <span>{item.remark}商品【{ item.goodsName}】的报价</span>
          //           <span>【波动方式：{item.priceType && this.priceTypeMap.find(l => l.value === item.priceType).desc};波动价格：{ item.price ? (item.price * 1).toFixed(2) : '0.00'}元；时效范围：{(item.startDt && item.endDt) && this.formatDate(item.startDt) + '~' + this.formatDate(item.endDt) }生效机构：{item.scopeOrgName} 】</span>
          //          </div>
          //        })}
          //       </div>
          //       /**
          //        <lb-table
          //           ref='lbTable'
          //           border
          //           element-loading-text='加载中'
          //           column={this.cols}
          //           data={row.detailList}
          //           pagination={false}
          //         />
          //       </div>*/
          //     )
          //   }
          // },
          { label: '', type: 'selection', align: 'center' },
          { label: '商品名称', prop: 'goodsName', align: 'center', width: 150, showOverflowTooltip: true },
          { label: '用户类型', prop: 'csmType', align: 'center', width: 110,
            render: (h, { row, column }) => { return row.csmType ? <span>{ row.csmType === 1 ? '居民用户' : '非居民用户' }</span> : '' }
          },
          { label: '配送费方案', prop: 'feeType', align: 'center', width: 110, showOverflowTooltip: true,
            render: (h, { row }) => <span>{ row.feeType && formatColumnMap(this.feeTypeMap, 'value', row.feeType, 'desc') }</span>
          },
          { label: '上楼费方案', prop: 'floorType', align: 'center', width: 110, showOverflowTooltip: true,
            render: (h, { row }) => <span>{ row.floorType && formatColumnMap(this.floorTypeMap, 'value', row.floorType, 'desc') }</span>
          },
          { label: '涉及用户', prop: 'containType', align: 'center', width: 90, showOverflowTooltip: true,
            render: (h, { row, column }) => { return row.containType ? <span>{ row.containType === 1 ? '所有客户' : '该大车司机的用户单独设置过价格的不涉及' }</span> : '' }
          },
          { label: '有效期', prop: 'scopeOrgName', align: 'center',
            showOverflowTooltip: true,
            render: (h, { row }) => {
              return (
                <div>
                  {(row.startDt && row.endDt) && <span>{ parseTime(row.endDt, '{y}') === '2099' ? '长期' : parseTime(row.startDt, '{y}-{m}-{d} {h}:{i}:{s}') + ' 至 ' + parseTime(row.endDt, '{y}-{m}-{d} {h}:{i}:{s}')}</span>}
                </div>
              )
            } },
          { label: '操作', prop: 'op', width: 60, align: 'center',
            render: (h, { row, column }) => <span v-show={!this.formDisabled} onClick={() => { this.del(row) }} style='color:red;cursor: pointer'>删除</span>
          }
        ]
      }
    },
    watch: {
      'resident.disCount1': {
        handler(newVal, oldVal) {
          // console.log('oldVal', oldVal)
          // console.log('newVal', newVal)
          if (this.resident.deliverList && this.resident.deliverList.length) {
            this.resident.deliverList = this.resident.deliverList
            return
          }
          this.changeResidentDistanceJson(newVal)
        },
        deep: true,
        immediate: true
      },
      'business.disCount1': {
        handler(newVal, oldVal) {
          // console.log('oldVal', oldVal)
          // console.log('newVal', newVal)
          if (this.business.deliverList && this.business.deliverList.length) {
            this.business.deliverList = this.business.deliverList
            return
          }
          this.changeBusinessDistanceJson(newVal)
        },
        deep: true,
        immediate: true
      },
      'dataForm.gtId': {
        handler(newVal, oldVal) {
          // console.log('oldVal', oldVal)
          // console.log('newVal', newVal)
          if (newVal) {
            this.goodsList = []
            this.getGoodsList()
          }
        },
        deep: true,
        immediate: true
      }
    },
    mounted() {

    },
    destroyed() {

    },
    methods: {
      async open(temp, type) {
        if (type === '查看') {
          this.formDisabled = true
          this.title = type
        }
        this.dataForm = {
          driverCode: temp.driverCode,
          driverName: temp.driverName,
          orgName: temp.orgName,
          timeType: null,
          goodsId: [],
          gtId: null,
          containType: null
        }
        await this.getGoodTypeList()
        return new Promise(resolve => {
          this.resolve = resolve
          if (temp) {
            this.temp = temp
            this.fetchData({ currentPage: 1, pageSize: 20 })
          }
          this.visible = true
        })
      },
      async getDriverPriceInfo(row) {
        const res = await queryDriverPriceInfo({ driverCode: row.driverCode, goodsId: row.goodsId, driverPriceCode: row.driverPriceCode })
        if (res.data) {
          const infoData = res.data
          this.resident = await infoData.filter(item => item.csmType === 1)[0]
          this.business = await infoData.filter(item => item.csmType === 2)[0]
          this.dataForm = await { ...res.data[0], goodsId: [res.data[0].goodsId] }
          if (this.dataForm.goodsId.length) {
            this.goodsChange(this.dataForm.goodsId)
          }
          // if (this.dataForm.goodsId) {
          //   this.goodsInfoList = []
          //   const goodsInfo = await this.goodsList.find(item => item.goodsId === this.dataForm.goodsId)
          //   console.log('goodsInfo', goodsInfo)
          //   this.goodsInfoList.push({ goodsId: goodsInfo.goodsId, goodsName: goodsInfo.goodsName, gtId: goodsInfo.gTypeId })
          // }

          // console.log('dataForm', res.data[0])
          // console.log('resident', this.resident)
          if (this.resident.deliverList && this.resident.deliverList.length) {
            this.resident.disCount1 = this.resident.deliverList.length
            this.resident.deliverList = this.resident.deliverList
          }
          // console.log('business', this.business)
          if (this.business.deliverList && this.business.deliverList.length) {
            this.business.disCount1 = this.business.deliverList.length
            this.business.deliverList = this.business.deliverList
          }

          if (parseTime(this.dataForm.endDt, '{y}') === '2099') {
            this.dataForm.timeType = 2
          } else {
            this.dataForm.timeType = 1
            this.date = [parseTime(this.dataForm.startDt, '{y}-{m}-{d} {h}:{i}:{s}'), parseTime(this.dataForm.endDt, '{y}-{m}-{d} {h}:{i}:{s}')]
          }
        }
      },
      // 修改居民配送费的类型
      changeResidentFee(value) {
        console.log(111)
        this.resident.disCount = null
        this.resident.fee = 0.00
        this.resident.distance = 0.00
        this.resident.exceedDistance = 0.00
        this.resident.fixedFee = 0.00
        this.resident.disCount1 = 2
        this.changeResidentDistanceJson(this.resident.disCount1)
      },
      // 修改非居民配送费的类型
      changeBusinessFee(value) {
        this.business.disCount = null
        this.business.fee = 0.00
        this.business.distance = 0.00
        this.business.exceedDistance = 0.00
        this.business.fixedFee = 0.00
        this.business.disCount1 = 2
        this.changeBusinessDistanceJson(this.business.disCount1)
      },
      // 修改居民上楼费
      changeResidentFloor(value) {
        this.resident.floorDisCount = null
        this.resident.floorFee = 0.00
      },
      // 修改非居民上楼费
      changeBusinessFloor(value) {
        this.business.floorDisCount = null
        this.business.floorFee = 0.00
      },
      // 修改生效时间
      changeTimeType(value) {
        if (value === 2) {
          this.resident.startDt = parseTime(new Date(), '{y}-{m}-{d} {h}:{i}:{s}')
          this.resident.endDt = '2099-01-01 00:00:00'
          this.business.startDt = parseTime(new Date(), '{y}-{m}-{d} {h}:{i}:{s}')
          this.business.endDt = '2099-01-01 00:00:00'
        } else {
          this.date = []
        }
        this.$forceUpdate()
      },
      // 配送费数据挡位起始值设置
      feeChange(val, index) {
        if (val[index].startDistance) {
          if (val[index].startDistance !== val[index - 1].endDistance) {
            this.$message.warning('起始值应等于截至值')
            val[index].startDistance = val[index - 1].endDistance
          }
        }
        if (!val[index].startDistance) {
          val[index].startDistance = val[index - 1].endDistance
        }
        if (!val[0].endDistance) {
          this.$message.error('第一档的截至值不能为零或空')
        }
        this.$forceUpdate()
      },
      // 配送费数据挡位截至值设置
      feeEndChange(val, index, parentVal) {
        if (val[index].endDistance) {
          if (val[index].endDistance < val[index].startDistance) {
            this.$message.warning('截至值不应小于起始值')
            val[index].endDistance = val[index].startDistance
          }
        }
        if (!val[index].endDistance) {
          val[index].endDistance = val[index].startDistance
        }
        if (!val[0].endDistance) {
          this.$message.error('第一档的截至值不能为零或空')
        }
        if ((index + 1) < val.length) {
          val[index + 1].startDistance = val[index].endDistance
        } else {
          parentVal.exceedDistance = val[index].endDistance
        }
        this.$forceUpdate()
      },
      // 保存
      async sumbit(formName, type) {
        if (this.dataForm.goodsId.length === 0) {
          this.$message.error('请选择商品')
          return
        }
        if (!this.resident.feeType) {
          this.$message.error('请选择居民配送费优惠方案')
          return
        }
        if (this.resident.feeType === 2 && this.resident.disCount === null) {
          this.$message.error('请选择市场价打折方案')
          return
        }
        // console.log(this.resident.fee)
        // console.log(this.resident.fee !== '')
        if (this.resident.feeType === 3 && this.resident.fee === undefined) {
          this.$message.error('请填写固定价格')
          return
        }
        let verifyFee1 = 0
        let verifyFee2 = 0
        if (this.resident.feeType === 4) {
          await this.resident.deliverList.forEach(item => {
            if (item.endDistance === undefined || item.endDistance === 0 || (item.endDistance === item.startDistance)) {
              verifyFee1++
            }
          })
        }
        if (this.business.feeType === 4) {
          await this.business.deliverList.forEach(item => {
            if (item.endDistance === undefined || item.endDistance === 0 || (item.endDistance === item.startDistance)) {
              verifyFee2++
            }
          })
        }
        if (verifyFee1) {
          this.$message.error('截至配送距离不能为零且不能等于起始配送距离')
          return
        }
        if (verifyFee2) {
          this.$message.error('截至配送距离不能为零且不能等于起始配送距离')
          return
        }
        if (this.resident.feeType === 4 && (!this.resident.exceedDistance === undefined || this.resident.fixedFee === undefined)) {
          this.$message.error('请填写完整按距离设置的居民配送费用')
          return
        }
        if (!this.business.feeType) {
          this.$message.error('请选择非居民配送费优惠方案')
          return
        }
        if (this.business.feeType === 2 && this.business.disCount === null) {
          this.$message.error('请选择市场价打折方案')
          return
        }
        if (this.business.feeType === 3 && this.business.fee === undefined) {
          this.$message.error('请填写固定价格')
          return
        }
        if (this.business.feeType === 4 && (this.business.exceedDistance === undefined || this.business.fixedFee === undefined)) {
          this.$message.error('请填写完整按距离设置的非居民配送费用')
          return
        }
        if (!this.resident.floorType) {
          this.$message.error('请选择居民上楼费优惠方案')
          return
        }
        if (this.resident.floorType === 2 && this.resident.floorDisCount === null) {
          this.$message.error('请选择市场价打折方案')
          return
        }
        if (this.resident.floorType === 3 && this.resident.floorFee === undefined) {
          this.$message.error('请填写固定价格')
          return
        }
        if (!this.business.floorType) {
          this.$message.error('请选择非居民上楼费优惠方案')
          return
        }
        if (this.business.floorType === 2 && this.business.floorDisCount === null) {
          this.$message.error('请选择市场价打折方案')
          return
        }
        if (this.business.floorType === 3 && this.business.floorFee === undefined) {
          this.$message.error('请填写固定价格')
          return
        }
        if (!this.dataForm.timeType) {
          this.$message.error('请选择生效日期')
          return
        }
        if (this.dataForm.timeType === 1 && this.date.length !== 2) {
          this.$message.error('请选择有效期范围')
          return
        }
        if (this.dataForm.timeType === 1) {
          this.resident.startDt = this.date[0]
          this.resident.endDt = this.date[1]
          this.business.startDt = this.date[0]
          this.business.endDt = this.date[1]
        } else {
          this.resident.startDt = parseTime(new Date(), '{y}-{m}-{d} {h}:{i}:{s}')
          this.resident.endDt = '2099-01-01 00:00:00'
          this.business.startDt = parseTime(new Date(), '{y}-{m}-{d} {h}:{i}:{s}')
          this.business.endDt = '2099-01-01 00:00:00'
        }
        if (!this.dataForm.containType) {
          this.$message.error('请选择涉及的大车用户')
          return
        }
        this.resident.csmType = 1
        this.resident.driverCode = this.dataForm.driverCode
        this.business.csmType = 2
        this.business.driverCode = this.dataForm.driverCode
        if (this.dataForm.driverPriceCode) {
          this.resident.driverPriceCode = this.dataForm.driverPriceCode
          this.business.driverPriceCode = this.dataForm.driverPriceCode
        }
        let rJson = []
        let bJson = []
        if (this.resident.feeType === 4) {
          // this.resident.deliverList = JSON.stringify(this.resident.deliverList)
          rJson = JSON.parse(JSON.stringify(this.resident.deliverList))
          this.resident.distanceJson = JSON.stringify(rJson)
        } else {
          this.resident.distanceJson = ''
        }
        if (this.business.feeType === 4) {
          // this.business.deliverList = JSON.stringify(this.business.deliverList)
          bJson = JSON.parse(JSON.stringify(this.business.deliverList))
          this.business.distanceJson = JSON.stringify(bJson)
        } else {
          this.business.distanceJson = ''
        }
        this.resident.containType = this.dataForm.containType
        this.business.containType = this.dataForm.containType
        this.resident.goodsInfoList = this.goodsInfoList
        this.business.goodsInfoList = this.goodsInfoList
        const infoList = [this.resident, this.business]
        // console.log('resident', this.resident)
        // console.log('business', this.business)
        // console.log('dataForm', this.dataForm)
        // console.log(this.date)
        const res = await saveDriverPrice(infoList)
        if (res.status === 200) this.$message.success(`保存成功`)
        this.visible = false
        this.parentFetchData()
      },
      // 查询列表
      async fetchData({ currentPage, pageSize }) {
        const query = {
          driverCode: this.temp.driverCode,
          expired: this.query.expired,
          currentPage,
          pageSize
        }
        const res = await queryDriverPriceInfoList(query)
        if (res.data) {
          this.tableData.data = await res.data.rows
          if (currentPage === 1) this.tableData.total = res.data.total
          if (this.dataForm.driverPriceCode) {
            const rows = await this.tableData.data.filter(item => item.driverPriceCode === this.dataForm.driverPriceCode)
            rows.forEach(row => {
              this.$refs.lbTable.toggleRowSelection(row)
            })
          }
        }
      },
      // 选中列表行
      async handleSelectionChange(selection, row) {
        // console.log('selection', selection)
        // console.log('row', row)
        if (this.query.expired === 1 && !this.formDisabled) {
          this.$message.error('该商品已过期')
          if (selection.length > 1) {
            await this.$refs.lbTable.clearSelection()
            this.$refs.lbTable.toggleRowSelection(row)
          }
          return
        }
        if (selection.length === 0) {
          await this.clearData()
          if (this.title === '查看') {
            this.formDisabled = true
            this.goodsDisabled = true
          }
          return
        }
        if (selection.length > 1) {
          await this.$refs.lbTable.clearSelection()
          this.$refs.lbTable.toggleRowSelection(row)
        }
        await this.getDriverPriceInfo(row)
        this.goodsDisabled = true
      },
      // 列表行详情
      async expandChange(row) {
        // const res = await CmsSpecialconfigUpdateDetail({
        //   categoryDetailId: row.categoryDetailId,
        //   csmId: row.csmId,
        //   pageSize: 10
        // })
        // this.$set(this.detailList, row.categoryDetailId, [])
        // this.$set(this.detailList, row.categoryDetailId, res.data)
      },
      objectSpanMethod({ row, column, rowIndex, columnIndex }) {
        if (columnIndex === 0 || columnIndex === 1 || columnIndex === 5 || columnIndex === 6 || columnIndex === 7) {
          if (rowIndex % 2 === 0) {
            return {
              rowspan: 2,
              colspan: 1
            }
          } else {
            return {
              rowspan: 0,
              colspan: 0
            }
          }
        }
      },
      // 删除
      del(row) {
        this.$confirm(`此操作会将司机设置的报价进行删除是否继续?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          dangerouslyUseHTMLString: true,
          type: 'warning'
        }).then(() => {
          deleteDriverPrice({ driverCode: row.driverCode, goodsId: row.goodsId, driverPriceCode: row.driverPriceCode }).then(res => {
            this.$notify({
              title: '提示',
              message: '删除成功!',
              type: 'success',
              duration: 2000
            })
            this.fetchData({ currentPage: 1, pageSize: 20 })
            this.clearData()
            this.parentFetchData()
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      },
      // 商品分类
      async getGoodTypeList() {
        const res = await goodsTypeQueryAllList({})
        this.goodTypeList = res.data
        this.dataForm.gtId = res.data[0].gtId
        this.getGoodsList()
      },
      // 商品列表
      async getGoodsList() {
        const res = await goodsTypeDetail({ gtId: this.dataForm.gtId })
        this.goodsList = res.data.rows
        // console.log(this.dataForm.goodsId)
        // console.log(this.goodsList)
        if (!this.dataForm.driverPriceCode) {
          this.dataForm.goodsId = []
        }
        if (this.goodsList.includes(item => item.goodsId !== this.dataForm.goodsId) && this.dataForm.driverPriceCode) {
          this.dataForm.goodsId = []
        }
      },
      async goodsTypeChange(value) {
        await this.getGoodsList()
      },
      async goodsChange(obj) {
        this.goodsInfoList = []
        obj.forEach(i => {
          const goodsInfo = this.goodsList.find(item => item.goodsId === i)
          this.goodsInfoList.push({ goodsId: goodsInfo.goodsId, goodsName: goodsInfo.goodsName, gtId: goodsInfo.gTypeId })
        })
      },
      // 改变居民档数
      changeResidentDistanceJson(value) {
        this.resident.deliverList = []
        for (let i = 0; i < value; i++) {
          const item = { startDistance: 0, endDistance: 0, fee: 0.00 }
          this.resident.deliverList.push(item)
        }
        this.$forceUpdate()
      },
      // 改变非居民档数
      changeBusinessDistanceJson(value) {
        this.business.deliverList = []
        for (let i = 0; i < value; i++) {
          const item = { startDistance: 0, endDistance: 0, fee: 0.00 }
          this.business.deliverList.push(item)
        }
        this.$forceUpdate()
      },
      // 清除数据
      async clearData() {
        await this.getGoodTypeList()
        this.formDisabled = false
        this.dataForm = {
          ...this.dataForm,
          driverPriceCode: '',
          timeType: null,
          containType: null,
          goodsId: []
        }
        this.multiple = true
        this.goodsDisabled = false
        // this.$set(this.dataForm, 'goodsId', null)
        this.resident = {
          disCount: null,
          fee: 0.00,
          exceedDistance: 0.00,
          fixedFee: 0.00,
          floorDisCount: null,
          floorFee: 0.00,
          disCount1: 2,
          feeType: 1,
          floorType: 1,
          deliverList: []
        }
        this.business = {
          disCount: null,
          fee: 0.00,
          exceedDistance: 0.00,
          fixedFee: 0.00,
          floorDisCount: null,
          floorFee: 0.00,
          disCount1: 2,
          feeType: 1,
          floorType: 1,
          deliverList: []
        }
        this.date = ''
      },
      // 重置
      reset() {
        this.formDisabled = false
        this.multiple = true
        this.goodsDisabled = false
        this.goodTypeList = []
        this.goodsList = []
        this.resident = {
          disCount: null,
          fee: 0.00,
          exceedDistance: 0.00,
          fixedFee: 0.00,
          floorDisCount: null,
          floorFee: 0.00,
          disCount1: 2,
          feeType: 1,
          floorType: 1,
          deliverList: []
        }
        this.business = {
          disCount: null,
          fee: 0.00,
          exceedDistance: 0.00,
          fixedFee: 0.00,
          floorDisCount: null,
          floorFee: 0.00,
          disCount1: 2,
          feeType: 1,
          floorType: 1,
          deliverList: []
        }
        this.dataForm = {
          driverCode: '',
          driverName: '',
          orgName: '',
          timeType: null,
          goodsId: [],
          gtId: null,
          containType: null
        }
        this.date = ''
        this.title = '设置'
        this.visible = false
        this.query.expired = 2
      },
      // 取消
      async cancel(formName) {
        await this.reset()
      }
    }
  }
</script>

<style lang='scss' scoped>
  .title {
    font-weight: 600;
  }
  .table-list {
    width: 100%;
    height: 200px;
    /deep/ .el-table {
      height: 165px !important;
      overflow: auto;
      .el-table__body-wrapper {
        height: auto !important;
      }
    }
    /deep/ .has-gutter {
      .el-checkbox {
        display: none;
      }
    }
  }
</style>
